/*
 * =====================================================================================
 *
 *       Filename:  getip.c
 *
 *    Description:  Get the owner IP with C
 *
 *        Version:  1.0
 *        Created:  09/28/15 09:27:33
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Andy (gk), andy_y_li@163.com
 *        Company:  RD
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <errno.h>
#include <netdb.h>

typedef enum {
    false,
    true
}bool;

bool getip(char *ipResult, int maxLen)
{
    bool flag = false;
    int sock;
    char **pptr = NULL;
    struct sockaddr_in destAddr;
    struct hostent *ptr = NULL;
    char destIP[128];
    char szBuffer[] = {"GET /ip2city.asp HTTP/1.1\r\nHost:www.ip138.com\r\nConnection:Close\r\n\r\n"};

    if (ipResult == NULL) {
        return flag;
    }

    // init the socket
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == sock) {
        printf("create socket failed: %s\n", strerror(errno));
        return flag;
    }

    bzero((void *)&destAddr, sizeof(destAddr));
    destAddr.sin_family = AF_INET;
    destAddr.sin_port = htons(80);

    // step 1, get the 'www.ip138.com' ip address
    ptr = gethostbyname("www.ip138.com");
    if (ptr == NULL) {
        printf("gethostbyname failed: %s\n", strerror(errno));
        return flag;
    }
    
    // step 2, try to connect the ip of ip138
    for (pptr = ptr->h_addr_list; NULL != *pptr; ++pptr) {
        inet_ntop(ptr->h_addrtype, *pptr, destIP, sizeof(destIP));
        printf("addr:%s\n", destIP);
        destAddr.sin_addr.s_addr = inet_addr(destIP);
        if (-1 != connect(sock, (struct sockaddr *)&destAddr, sizeof(struct sockaddr))) {
            flag = true;
            break;
        }
    }

    if (false == flag) {
        printf("connect error:%s\n", strerror(errno));
        return flag;
    }

    // step 3, send ip package
    if (strlen(szBuffer) != send(sock, szBuffer, strlen(szBuffer), 0)) {
        printf("send error:%s\n", strerror(errno));
        return false;
    }

    // step 4, recv the data
    if (-1 == recv(sock, ipResult, maxLen, 0)) {
        printf("recv error:%s\n", strerror(errno));
        return false;
    }
    return true;
}

int main()
{
    bool ret = false;
    char ipResult[1024];
    ret = getip(ipResult, 1023);
    if (ret == false) {
        printf("getip fail\n");
    }
    else {
        printf("The ip is %s\n", ipResult);
    }
}

